package JUC.第06章_内存模型之JMM;

import org.junit.Test;


public class JMM {    //java内存模型  //主类


    private static volatile JMM instance = null; //加volatile禁止指令重排
    private JMM() {
        System.out.println(Thread.currentThread().getName() + "\t我是构造方法");
    }
    public static JMM getInstance() {
        if(instance == null){
            synchronized (JMM.class){   //锁加在这里  在多线程下有可能指令重排 会先执行return
                if(instance == null)//实现单例模式
                instance = new JMM();
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                JMM.getInstance();
            },String.valueOf(i+1)).start();
        }
        System.out.println(JMM.getInstance() == JMM.getInstance());
        System.out.println(JMM.getInstance() == JMM.getInstance());
        System.out.println(JMM.getInstance() == JMM.getInstance());

    }
    @Test
    public void 构造函数_的多线程应用() {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                System.out.println(JMM.getInstance());
            },String.valueOf(i+1)).start();
        }
        System.out.println(JMM.getInstance() == JMM.getInstance());
        System.out.println(JMM.getInstance() == JMM.getInstance());
        System.out.println(JMM.getInstance() == JMM.getInstance());


    }


}
